package mylibrary.thread.blockingQueue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;

public class SearchTask implements Runnable {

	private BlockingQueue queue;
	private String keyWord;
	
	public SearchTask(BlockingQueue queue, String keyWord) {
		this.queue = queue;
		this.keyWord = keyWord;
	}
	
	public void run() {
		try{
			boolean done = false;
			while(!done) {
				File file = (File)queue.take();
				
				if(file == FileEnumerationTask.DUMMY) {
					queue.put(file);
					done = true;
				} else {
					search(file);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void search(File file) throws FileNotFoundException {
		Scanner in = new Scanner(new FileInputStream(file));
		int lineNumber = 0;
		while(in.hasNextLine()) {
			lineNumber++;
			String line = in.nextLine();
			if(line.contains(keyWord)) {
				System.out.println(file.getPath() + " " + lineNumber + " - " + Thread.currentThread().getName());
				
			}
		}
		in.close();
	}
}
